package com.hjm.ui.common.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Map;

public abstract class BaseAdapter extends RecyclerView.Adapter<BaseViewHolder> {
    Map<Integer, Class<?>> viewClassMap;
    Map<Integer, Object> valueMap;
    List<Object> objectList;

    private Context context;

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getInflateLayout(), parent, false);
        viewClassMap = getViewClassMap();
        valueMap = getValueMap();
        return new BaseViewHolder(view, viewClassMap);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        Object object = objectList.get(position);

        for (Map.Entry<Integer, Class<?>> entry : viewClassMap.entrySet()) {
            if(holder.viewMap.get(entry.getKey()) instanceof ImageView) {
                ImageView imageView = (ImageView) holder.viewMap.get(entry.getKey());
                if(valueMap.get(entry.getKey()) instanceof Integer) {
                    imageView.setImageResource((Integer) valueMap.get(entry.getKey()));
                }
            } else if (holder.viewMap.get(entry.getKey()) instanceof TextView){
                TextView textView = (TextView) holder.viewMap.get(entry.getKey());
                if(valueMap.get(entry.getKey()) instanceof String) {
                    textView.setText((String) valueMap.get(entry.getKey()));
                }
            }
        }

        onBind(holder, object);
    }

    @Override
    public int getItemCount() {
        return objectList.size();
    }

    public BaseAdapter(Map<Integer, Class<?>> viewClassMap, Map<Integer, Object> valueMap, List<Object> objectList, Context context) {
        this.viewClassMap = viewClassMap;
        this.valueMap = valueMap;
        this.objectList = objectList;
        this.context = context;
    }

    // 抽象方法，子类需要实现
    abstract int getInflateLayout();

    abstract Map<Integer, Class<?>> getViewClassMap();

    abstract Map<Integer, Object> getValueMap();

    abstract void onBind(BaseViewHolder holder, Object object);
}
